package com.example.shop_2207.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.shop_2207.R
import com.example.shop_2207.database.MyDbUtils
import com.example.shop_2207.databinding.FragmentMineBinding
import com.example.shop_2207.entity.UserEntity
import com.example.shop_2207.mvvm.BaseFragment
import com.example.shop_2207.mvvm.BaseViewFragment
import com.example.shop_2207.net.GlideUtils
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class MineFragment : BaseFragment<FragmentMineBinding,MineViewModel>() {
    lateinit var user:UserEntity
    override fun getLayout(): Int  = R.layout.fragment_mine
    override fun getViewModel(): Class<MineViewModel>  = MineViewModel::class.java

    override fun initView() {
        //查询数据库，展示我的个人信息
        user = MyDbUtils.getDb().getUserDao().queryUserById(SPUtils.getInstance().getInt("user_id"))
       /* binding.userName.setText(user.username)
        Glide.with(requireContext()).load(user.icon).into(binding.userIv)*/
        binding.user = user

        binding.logout.setOnClickListener {
            SPUtils.getInstance().clear()
            ARouter.getInstance().build("/app/LoginActivity").navigation()
        }

        val navHostFragment = childFragmentManager.findFragmentById(R.id.fragmentContainerView2) as NavHostFragment
        val navController = navHostFragment.navController
        binding.bottomMine.setupWithNavController(navController)

        binding.userIv.setOnClickListener {
            PictureSelector.create(this,200).selectPicture()
        }

        //弹出框的点击事件
        binding.tv.setOnClickListener {
            //弹出日期选择框
           /* val datePicker = DatePicker(requireActivity())
            datePicker.setTitle("请选择出生年月")
            //设置时间范围
            datePicker.wheelLayout.setRange(DateEntity.target(1900,1,1), DateEntity.target(9999,12,31))
            //设置默认时间
            datePicker.wheelLayout.setDefaultValue(DateEntity.today())
            datePicker.setOnDatePickedListener { year, month, day ->
                ToastUtils.showLong("$year -$month -$day")
            }
            datePicker.show()*/
            //弹出选项选择框
           /* val list = mutableListOf<String>()
            list.add("男")
            list.add("女")
            list.add("保密")
            val optionPicker = OptionPicker(requireActivity())
            optionPicker.setTitle("请选择性别")
            optionPicker.setData(list)
            optionPicker.setDefaultPosition(0)
            optionPicker.setOnOptionPickedListener { position, item ->
                ToastUtils.showLong("选中的是${list[position]}")
                //更新服务器中的数据
            }
            optionPicker.show()*/
            //弹出地址选择框
            val addressPicker = AddressPicker(requireActivity())
            addressPicker.setTitle("请选择配送地址")
            addressPicker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            addressPicker.setOnAddressPickedListener { province, city, county ->
                ToastUtils.showLong("选中的地址为${province.name}-${city.name}-${county.name}")
            }
            addressPicker.show()

        }


    }

    override fun initData() {
        viewModel.iconSuccess.observe(this){
            ToastUtils.showLong(it.message)
            if(it.code==200){
                user.icon = it.data.toString()
                //更新数据用户头像
                MyDbUtils.getDb().getUserDao().updateUser(user)
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==200&&resultCode==Activity.RESULT_OK){
            if (data != null) {
                val picture = data.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
                //更新页面图片
                context?.let { GlideUtils.loadCircleImage(it,picture.path,binding.userIv) }
                //更新服务器上的图片
                val body = RequestBody.create("multipart/form-data".toMediaType(), File(picture.path))
                val part = MultipartBody.Part.createFormData("file","abc.jpg",body)
                viewModel.updateIcon(part)
            }
        }
    }
}